<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Tymon\JWTAuth\Facades\JWTAuth;

class AdminAuthController extends Controller
{
    // 管理员登录API
    public function login(Request $request)
    {
        $request->validate([
            'mobile' => 'required|string',
            'password' => 'required|string',
        ]);

        $credentials = $request->only('mobile', 'password');

        if (!Auth::attempt($credentials)) {
            return response()->json(['message' => '手机号或密码错误'], 401);
        }

        $user = Auth::user();
        
        // 验证管理员权限
        if (!$user->is_admin) {
            Auth::logout();
            return response()->json(['message' => '需要管理员权限'], 403);
        }

        // 生成令牌（使用现有JWT逻辑）
        $token = JWTAuth::fromUser($user);

        return response()->json([
            'access_token' => $token,
            'token_type' => 'Bearer',
            'user' => $user
        ]);
    }
    // 管理员注册API
public function register(Request $request)
{
    $request->validate([
        'mobile' => 'required|string|unique:users,mobile',
        'password' => 'required|string|min:6|confirmed',
        'name' => 'required|string|max:255'
    ]);

    $user = User::create([
        'mobile' => $request->mobile,
        'password' => bcrypt($request->password),
        'name' => $request->name,
        'is_admin' => true // 标记为管理员
    ]);

    // 自动登录并返回令牌（可选）
    $token = JWTAuth::fromUser($user);

    return response()->json([
        'message' => '管理员账号创建成功',
        'access_token' => $token,
        'token_type' => 'Bearer',
        'user' => $user
    ], 201);
}

    // 管理员退出
    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();
        return response()->json(['message' => '成功退出']);
    }
}